﻿using System;

using VSTalk.Engine.Core.XmppCommunication;
using VSTalk.Engine.Core.XmppCommunication.Services.RoomManager;
using VSTalk.Engine.Utils;
using VSTalk.Model;

namespace VSTalk.Engine.ViewModel.Editors.RoomEditor
{
    public class RoomEditorViewModel
    {
        private readonly Client _client;

        public event Action Rejected;

        public event Action Saved;

        public IRoomInfo Model { get; private set; }

        public RelayCommand SaveChanges { get; private set; }

        public RelayCommand RejectChanges { get; private set; }

        private IRoomManager _roomManager;
        public IRoomManager RoomManager
        {
            get { return _roomManager ?? (_roomManager = CommunicationServiceFactory.Create<RoomManager>(_client)); }
        }

        public RoomEditorViewModel(Client client)
        {
            _client = client;
            Model = new RoomInfo();
            SetCommands();
        }

        private void SetCommands()
        {
            SaveChanges = new RelayCommand(SaveChangesExecuted, SaveChangesCanExecute);
            RejectChanges = new RelayCommand(RejectChangesExecuted);
        }

        private bool SaveChangesCanExecute()
        {
            return !string.IsNullOrEmpty(Model.Nickname) &&
                   !string.IsNullOrEmpty(Model.RoomName) &&
                   !string.IsNullOrEmpty(Model.Server);
        }

        private void RejectChangesExecuted()
        {
            OnRejected();
        }

        private void SaveChangesExecuted()
        {
            RoomManager.AddRoom(Model);
            OnSaved();
        }

        protected virtual void OnSaved()
        {
            var handler = Saved;
            if (handler != null) handler();
        }

        protected virtual void OnRejected()
        {
            var handler = Rejected;
            if (handler != null) handler();
        }
    }
}